package com.yf.stat.modules.total.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yf.base.api.api.ApiRest;
import com.yf.base.api.api.controller.BaseController;
import com.yf.base.api.api.dto.PagingReqDTO;
import com.yf.base.utils.DateUtils;
import com.yf.stat.modules.total.dto.StatTotalExamDTO;
import com.yf.stat.modules.total.dto.request.StatTotalExamReqDTO;
import com.yf.stat.modules.total.service.StatTotalExamService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Calendar;
import java.util.List;

/**
* <p>
* 考试统计控制器
* </p>
*
* @author 聪明笨狗
* @since 2021-06-04 09:08
*/
@Api(tags={"考试统计"})
@RestController
@RequestMapping("/api/stat/total/exam")
public class StatTotalExamController extends BaseController {

    @Autowired
    private StatTotalExamService baseService;


    /**
     * 分页查找
     * @param reqDTO
     * @return
     */
    @ApiOperation(value = "分页查找")
    @PostMapping("/paging")
    public ApiRest<IPage<StatTotalExamDTO>> paging(@RequestBody PagingReqDTO<StatTotalExamReqDTO> reqDTO) {



        StatTotalExamReqDTO params = reqDTO.getParams();

        if(params==null){
            params = new StatTotalExamReqDTO();
        }

        if(StringUtils.isBlank(params.getStartDate())
                || StringUtils.isBlank(params.getEndDate())){
            this.fillDateQuery(params, -30);
        }

        params.setOrderType("DESC");

        //分页查询并转换
        IPage<StatTotalExamDTO> page = baseService.paging(reqDTO);

        return super.success(page);
    }

    /**
     * 查找最近一周数据，用于控制台图表显示
     * @return
     */
    @ApiOperation(value = "查找最近一周数据")
    @PostMapping("/week")
    public ApiRest<List<StatTotalExamDTO>> week() {


        StatTotalExamReqDTO query = new StatTotalExamReqDTO();
        this.fillDateQuery(query, -6);
        query.setOrderType("ASC");

        PagingReqDTO<StatTotalExamReqDTO> reqDTO = new PagingReqDTO<>();
        reqDTO.setParams(query);
        reqDTO.setCurrent(1);
        reqDTO.setSize(7);

        IPage<StatTotalExamDTO> page = baseService.paging(reqDTO);
        return super.success(page.getRecords());
    }

    /**
     * 填充本周时间
     * @param params
     */
    private void fillDateQuery(StatTotalExamReqDTO params, int day){
        params.setEndDate(DateUtils.dateNow("yyyy-MM-dd"));
        Calendar cl = Calendar.getInstance();
        cl.setTimeInMillis(System.currentTimeMillis());
        cl.add(Calendar.DATE, day);
        params.setStartDate(DateUtils.formatDate(cl.getTime(), "yyyy-MM-dd"));
    }
}
